<template>
  <div class="dashboard-container">
<el-container>
  <el-header class="dashboard-header">
    <div class="header-content">
      <div class="logo-title">
        <img src="@/assets/logo.png" alt="Logo" class="header-logo">
        <span>简历分析系统 - 用户面板</span>
      </div>
      <div>
        <el-button @click="$router.push('/change-password')" type="text">修改密码</el-button>
        <el-button @click="logout" type="text">退出登录</el-button>
      </div>
    </div>
  </el-header>
      <el-main>
        <el-tabs v-model="activeTab">
          <el-tab-pane label="上传简历" name="upload">
            <el-upload
              class="upload-demo"
              drag
              action=""
              :auto-upload="false"
              :on-change="handleFileChange"
              :file-list="fileList">
              <el-icon class="el-icon--upload"><upload-filled /></el-icon>
              <div class="el-upload__text">
                拖拽文件到此处或<em>点击上传</em>
              </div>
              <template #tip>
                <div class="el-upload__tip">
                  支持PDF/DOCX/TXT格式，大小不超过10MB
                </div>
              </template>
            </el-upload>
            <el-input
              v-model="resumeText"
              type="textarea"
              :rows="10"
              placeholder="或者直接输入简历内容..."
              class="resume-textarea"
            />
            <el-button type="primary" @click="analyzeResume">分析简历</el-button>
          </el-tab-pane>
          <el-tab-pane label="分析结果" name="result" v-if="analysisResult">
          <el-tab-pane label="职位搜索" name="jobSearch">
            <div class="search-section">
              <el-input
                v-model="jobSearchQuery"
                placeholder="输入技能关键词搜索职位"
                class="search-input"
              />
              <el-button 
                type="primary" 
                @click="searchJobs"
                :loading="jobSearchLoading">
                搜索职位
              </el-button>
            </div>
            <div class="result-section" v-if="jobSearchResults">
              <h3>职位搜索结果</h3>
              <el-table :data="jobSearchResults" style="width: 100%">
                <el-table-column prop="title" label="职位" />
                <el-table-column prop="company" label="公司" />
                <el-table-column prop="description" label="描述" />
                <el-table-column prop="score" label="匹配度" />
              </el-table>
            </div>
          </el-tab-pane>
          <el-tab-pane label="技能搜索" name="skillSearch">
            <div class="search-section">
              <el-input
                v-model="skillSearchQuery"
                placeholder="输入技能关键词搜索相关技能"
                class="search-input"
              />
              <el-button 
                type="primary" 
                @click="searchSkills"
                :loading="skillSearchLoading">
                搜索技能
              </el-button>
            </div>
            <div class="result-section" v-if="skillSearchResults">
              <h3>技能搜索结果</h3>
              <el-tag
                v-for="skill in skillSearchResults"
                :key="skill.name"
                type="info"
                class="skill-tag">
                {{ skill.name }} (相关度: {{ skill.score }})
              </el-tag>
            </div>
          </el-tab-pane>
          <el-tab-pane label="RAG统计" name="ragStats">
            <div class="result-section" v-if="ragStats">
              <h3>RAG系统统计</h3>
              <el-descriptions border>
                <el-descriptions-item label="简历数量">{{ ragStats.resume_count }}</el-descriptions-item>
                <el-descriptions-item label="职位数量">{{ ragStats.job_count }}</el-descriptions-item>
                <el-descriptions-item label="技能数量">{{ ragStats.skill_count }}</el-descriptions-item>
                <el-descriptions-item label="最后更新时间">{{ ragStats.last_updated }}</el-descriptions-item>
              </el-descriptions>
            </div>
            <el-button 
              type="primary" 
              @click="loadRagStats"
              :loading="ragStatsLoading">
              刷新统计
            </el-button>
          </el-tab-pane>
            <div class="result-section">
              <h3>技能分析</h3>
              <el-tag 
                v-for="skill in analysisResult.skills" 
                :key="skill"
                type="success"
                class="skill-tag">
                {{ skill }}
              </el-tag>
            </div>
            <div class="result-section">
              <h3>推荐岗位</h3>
              <el-table :data="analysisResult.recommendedJobs" style="width: 100%">
                <el-table-column prop="title" label="职位" />
                <el-table-column prop="company" label="公司" />
                <el-table-column prop="match" label="匹配度" />
              </el-table>
            </div>
            <div class="result-section">
              <h3>面试建议</h3>
              <el-collapse>
                <el-collapse-item 
                  v-for="(advice, index) in analysisResult.interviewAdvice" 
                  :key="index"
                  :title="advice.title">
                  {{ advice.content }}
                </el-collapse-item>
              </el-collapse>
            </div>
          </el-tab-pane>
        </el-tabs>
      </el-main>
    </el-container>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { UploadFilled } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/stores/user'
import axios from 'axios'

const userStore = useUserStore()
const activeTab = ref('upload')
const fileList = ref([])
const resumeText = ref('')
const analysisResult = ref(null)
const jobSearchQuery = ref('')
const jobSearchResults = ref(null)
const jobSearchLoading = ref(false)
const skillSearchQuery = ref('')
const skillSearchResults = ref(null)
const skillSearchLoading = ref(false)
const ragStats = ref(null)
const ragStatsLoading = ref(false)

const logout = () => {
  userStore.logout()
}

const handleFileChange = async (file) => {
  try {
    const formData = new FormData()
    formData.append('file', file.raw)
    const response = await axios.post('/api/upload', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
    ElMessage.success(response.data.message)
    fileList.value = [file]
  } catch (error) {
    console.error('Upload error details:', {
      message: error.message,
      response: error.response,
      request: error.request
    })
    ElMessage.error(error.response?.data?.error || '上传失败')
  }
}

const searchJobs = async () => {
  try {
    jobSearchLoading.value = true
    const res = await axios.post('/api/rag/search_jobs', {
      content: jobSearchQuery.value,
      n_results: 5
    })
    jobSearchResults.value = res.data.results
  } catch (error) {
    console.error('Job search error:', error)
    ElMessage.error(error.response?.data?.error || '职位搜索失败')
  } finally {
    jobSearchLoading.value = false
  }
}

const searchSkills = async () => {
  try {
    skillSearchLoading.value = true
    const res = await axios.post('/api/rag/search_skills', {
      content: skillSearchQuery.value,
      n_results: 10
    })
    skillSearchResults.value = res.data.results
  } catch (error) {
    console.error('Skill search error:', error)
    ElMessage.error(error.response?.data?.error || '技能搜索失败')
  } finally {
    skillSearchLoading.value = false
  }
}

const loadRagStats = async () => {
  try {
    ragStatsLoading.value = true
    const res = await axios.get('/api/rag/stats')
    ragStats.value = res.data
  } catch (error) {
    console.error('RAG stats error:', error)
    ElMessage.error(error.response?.data?.error || '获取统计失败')
  } finally {
    ragStatsLoading.value = false
  }
}

const analyzeResume = async () => {
  try {
    let content = resumeText.value
    if (!content && fileList.value.length > 0) {
      // 上传文件并获取内容
      const formData = new FormData()
      formData.append('file', fileList.value[0].raw)
      const uploadRes = await axios.post('/api/upload', formData, {
        headers: { 'Content-Type': 'multipart/form-data' }
      })
      // 确保content是字符串
      content = typeof uploadRes.data.resume_data === 'string' 
        ? uploadRes.data.resume_data
        : JSON.stringify(uploadRes.data.resume_data)
    } else if (typeof content !== 'string') {
      content = JSON.stringify(content)
    }

    if (!content) {
      ElMessage.warning('请上传简历或输入简历内容')
      return
    }

    // 并行调用API
    const [analysisRes, jobsRes, adviceRes] = await Promise.all([
      axios.post('/api/agent/analyze_resume', { content }),
      axios.post('/api/agent/recommend_jobs', { content, n_results: 3 }),
      axios.post('/api/agent/interview_advice', { content })
    ])

    // 更新结果
    analysisResult.value = {
      skills: analysisRes.data.skills,
      recommendedJobs: jobsRes.data.jobs,
      interviewAdvice: adviceRes.data.advice
    }
    activeTab.value = 'result'
    ElMessage.success('分析完成')
  } catch (error) {
    console.error('Analysis error:', error)
    ElMessage.error(error.response?.data?.error || '分析失败')
  }
}
</script>

<style scoped>
.dashboard-container {
  min-height: 100vh;
  background: #f5f7fa;
  padding: 20px;
}
.dashboard-header {
  background: #fff;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  border-bottom: 1px solid #ebeef5;
}
.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 100%;
  padding: 0 20px;
}
.header-content > div {
  display: flex;
  gap: 10px;
}
.logo-title {
  display: flex;
  align-items: center;
  gap: 15px;
}
.header-logo {
  height: 50px;
}
.upload-demo {
  width: 100%;
  max-width: 800px;
  margin: 0 auto 40px;
  padding: 30px;
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}
.resume-textarea {
  margin: 0 auto 40px;
  width: 100%;
  max-width: 800px;
}
.resume-textarea :deep(.el-textarea__inner) {
  min-height: 200px;
  padding: 15px;
  border-radius: 8px;
}
.result-section {
  margin-bottom: 40px;
  padding: 25px;
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}
.result-section h3 {
  color: #2c3e50;
  margin-bottom: 20px;
  font-size: 18px;
  font-weight: 600;
}
.skill-tag {
  margin-right: 10px;
  margin-bottom: 10px;
}

.search-section {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
  max-width: 800px;
  margin: 0 auto 20px;
}

.search-input {
  flex: 1;
}

.search-input :deep(.el-input__inner) {
  height: 40px;
  border-radius: 8px;
}

.el-descriptions {
  margin-bottom: 20px;
}
</style>
